package com.xjscrm.console.chat.mq.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendTalkMsg;
import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.console.chat.enums.ChatTalkRecordSource;
import com.xjscrm.console.chat.mq.MQSender;
import com.xjscrm.console.chat.mq.MsgHandler;
import com.xjscrm.console.chat.mq.dto.DispatchDTO;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.group.WwGroupService;
import com.xjscrm.console.service.customer.wwCustomer.WwCustomerService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/11 18:14
 */
@Component
@Slf4j
public class TalkFriendMsgHandler extends TalkMsgHandler implements MsgHandler<MicaFriendTalkMsg> {

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private WwGroupService wwGroupService;
    @Autowired
    private WwCustomerService wwCustomerService;

    @Autowired
    private ChatTalkRecordService chatTalkRecordService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Override
    public MicaMsgType msgType() {
        return MicaMsgType.TALK_FRIEND;
    }

    @Override
    public Class<MicaFriendTalkMsg> msgClass() {
        return MicaFriendTalkMsg.class;
    }

    @Override
    @Transactional
    public void doHandle(MicaFriendTalkMsg micaFriendTalkMsg) {

        log.info("TalkFriend: {}", JSON.toJSONString(micaFriendTalkMsg));


        MicaTransDto micaTransDto = baseCache.get();
        Long merId = micaTransDto.getMerId();
        String deviceId = micaTransDto.getDeviceId();
        Integer deviceType = micaTransDto.getDeviceType();

        if (endWithTaskTrigger(merId, micaFriendTalkMsg.getTaskId())) {
            return;
        }

        String conversationId = micaFriendTalkMsg.getConversationId();
        if (!ObjectUtils.allNotNull(conversationId, merId, deviceType) || StringUtils.isBlank(deviceId)) {
            log.error("TalkFriend info is illegal");
            return;
        }

        WwDevice wwDevice = wwDeviceService.getByDeviceId(merId, deviceId);
        if (Objects.isNull(wwDevice) || Objects.equals(wwDevice.getOpenChat(), 0)) {
            log.error("TalkFriend device not found or not open chat: {}", deviceId);
            return;
        }
        Long talkRecordId = IdUtil.getSnowflakeNextId();
        //
        ChatTalkSession talkSession = super.addSessionIfAbsentWithUpdate(merId, talkRecordId, wwDevice, micaFriendTalkMsg);
        if (Objects.isNull(talkSession)) {
            return;
        }
        //
        ChatTalkRecord chatTalkRecord = super.build(micaFriendTalkMsg, talkSession);
        chatTalkRecord.setId(talkRecordId);
        chatTalkRecord.setSource(ChatTalkRecordSource.reply.getCode());
        // 新增聊天记录
        chatTalkRecordService.add(chatTalkRecord);
        //
        log.info("TalkFriend session and record is save success; next dispatch message: talkSessionId: {}; talkRecordId: {}", talkSession.getId(), chatTalkRecord.getId());
        // 分发
        DispatchDTO dispatchDTO = new DispatchDTO();

        dispatchDTO.setMerId(merId);
        dispatchDTO.setDeviceUniqueId(wwDevice.getId());
        dispatchDTO.setTalkSessionId(talkSession.getId());
        dispatchDTO.setTalkRecordId(chatTalkRecord.getId());

        MQSender.sendMQMsg("XJ_WW_DISPATCH_TOPIC", dispatchDTO);
        //
        /*rocketMQTemplate.asyncSend("XJ_WW_DISPATCH_TOPIC", MessageBuilder.withPayload(dispatchDTO).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送分发消息成功 -> topic:{}, msg:{}", "XJ_WW_DISPATCH_TOPIC", JSON.toJSONString(dispatchDTO));
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("发送分发消息失败 > exception", throwable);
            }
        });*/
    }

    private boolean endWithTaskTrigger(Long merId, Long recordId) {
        if (Objects.isNull(merId) || Objects.isNull(recordId)) {
            return false;
        }
        ChatTalkRecord talkRecord = chatTalkRecordService.getById(merId, recordId);
        return Objects.nonNull(talkRecord);
    }
}
